package cn.z2huo.leetcode.problem.NO_0006;

import java.util.*;

public class Solution {
	
	//将所得字符串按照指定格式输出
	public void convert(String str, int row) {
		//判断二维数组有几行几列
		int length;
		int column;
		length = str.length();
		column = length/(2*row-2)*(row-1);
		//正好整除的情况下
		if(length%(2*row-2) == 0) {
		//没有斜线的情况下
		}else if(length%(2*row-2) < row) {
			column ++;
		//刚好到达尽头或者有斜线的情况下
		}else if(length%(2*row-2) >= row) {
			column ++;
			if(length%(2*row-2) > row) {
				column += length%(2*row-2)-row;
			}
		}
		
		//行列颠倒
		char[][] demo = new char[column][row];
		int b = 2;
		for(int i=0,a=0; i<column; i++) {
			for(int j=0; j<row; j++) {
				//放竖
				if(i%(row-1) == 0) {
					demo[i][j] = str.charAt(a);
					if(a<length-1) {
						a ++;
					}
				//放斜
				}else {
					//先将所有的都设置为空格，空格的asc2码是32
					for(int m=row-1; m<row&&m>=0; m--) {
						demo[i][m] = 32;
					}
					demo[i][row-b] = str.charAt(a);
					if(a<length-1) {
						a ++;
					}
					if(row-b == 1) {	//当斜到达末端时，重置b的值
						b = 2;
						break;
					}
					b ++;
					break;
				}
			}
		}
		printArray(demo,column,row);
	}
	//将数组打印输出
	public void printArray(char[][] demo, int column, int row) {
		for(int i=0; i<column; i++) {
			for(int j=0; j<row; j++) {
				System.out.print(" "+demo[i][j]+" ");
			}
			System.out.println();
		}
	}
	
	//将字符串按照制定的字符串格式输出
	public String change(String str, int row) {
		String result = null;
		char[] demo = new char[str.length()];
		
		char[] flag = str.toCharArray();
		int nowDemo = 1;
		int nowFlag = 0;
		int nowSub = 2*row-2;
		for(int i=0,j=0; i<demo.length&&j<row; i++) {
			if(j == 0) {
				if(nowFlag == 0) {
					demo[i] = flag[j];
					nowFlag = nowSub*nowDemo;
				}else if(nowFlag > demo.length) {
					nowFlag = 0;
					nowDemo = 1;
					j ++;
					i --;
				}else {
					demo[i] = flag[nowFlag];
					nowDemo ++;
					nowFlag = nowSub*nowDemo;
				}
			}else if(j == row) {
				
			}else {
				if(nowFlag == 0) {
					demo[i] = flag[j];
					nowFlag = j+nowSub-2*nowDemo;
				}else if(nowFlag > demo.length) {
					nowFlag = 0;
					nowDemo = 1;
					j++;
					i--;
				}else {
					demo[i] = flag[nowFlag];
					nowDemo ++;
					nowFlag += nowSub-2*nowDemo;
					if(nowSub-2*nowDemo <= 2) {
						nowDemo = 0;
					}
				}
			}
		}
		
		return result;
	}
	
	public static void main(String[] args) {
		String str = null;
		int row = 0;
		
		Solution s = new Solution();
		Scanner sc = new Scanner(System.in);
		
		System.out.println("请输入您的字符串：");
		str = sc.nextLine();
		System.out.println("请输入您想要的行数：");
		while(row < 2) {
			System.out.println("行数必须大于2！");
			row = sc.nextInt();
		}
		sc.close();
		s.convert(str, row);
		System.out.println("按照题目格式输出：");
		s.change(str, row);
	}
}
